<template>
  <el-dialog title="上传文件" :visible.sync="dialogVisible" width="462px" @closed="handleClose">
    <el-form
      ref="formData"
      class="driverPrgramForm"
      :model="formData"
      :rules="rules"
      label-suffix="："
      :label-width="'121px'"
    >
      <el-form-item label="上传文件类型" prop="relationTypeId">
        <el-select
          v-model="formData.relationTypeId"
          clearable
          style="width: 100%"
          placeholder="请选择上传文件类型"
        >
          <el-option
            v-for="item in driverFileTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="'上传文件'" prop="driverFiles">
        <el-upload
          ref="driverFiles"
          class="upload-demo"
          action="#"
          multiple
          :disabled="!formData.relationTypeId"
          :accept="uploadFileType"
          :file-list="formData.driverFiles"
          :on-exceed="handleExceed"
          :on-remove="() => handleRemove('driverFiles')"
          :http-request="(require) => handleUploadFiles(require, 'driverFiles')"
        >
          <div v-show="formData.relationTypeId" slot="tip" class="el-upload__tip">
            <template v-if="uploadFileType">只能上传{{ uploadFileType }}文件，且单个文件不超过 20 MB</template>
            <template v-else>上传文件不超过 20 MB</template>
          </div>
          <el-button size="small" plain :disabled="!formData.relationTypeId">
            上传文件
            <i class="el-icon-upload el-icon--right" />
          </el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeForm()">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addDriverFile } from '@/api/project-management'
import { uploadFile } from '@/api/system-management'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'

export default {
  name: 'AddDriverFile',
  components: {},
  inheritAttrs: false,
  data() {
    return {
      dialogVisible: false,
      driverFileTypeList: [
        {
          label: '.h头文件',
          value: 27,
          accept: '.h'
        },
        {
          label: '.c源文件',
          value: 28,
          accept: '.c'
        },
        {
          label: '其他驱动文件',
          value: 30
        },
        {
          label: '说明文档',
          value: 29
        }
      ],
      formData: {
        relationTypeId: '',
        driverFiles: []
      },
      rules: {
        relationTypeId: [{ required: true, message: '请选择上传文件类型', trigger: ['change', 'blur'] }],
        driverFiles: [{ type: 'array', required: true, message: '请上传文件', trigger: 'change' }]
      },

      masterChipArray: [],
      slaveChipArray: [],
      getChipListRequestId: generateUUID(),
      uploadFileRequestId: generateUUID(),
      currentUploadFile: {},
      addDriverFileRequestId: generateUUID()
    }
  },
  computed: {
    uploadFileType() {
      return this.driverFileTypeList.find((item) => item.value === this.formData.relationTypeId)?.accept
    }
  },
  mounted() {
    receivedMessage(this.dataHandle)
  },
  methods: {
    dataHandle(result) {
      let self = this
      let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
      if (e.data.webInfo.requestId === self.uploadFileRequestId) {
        self.formData[self.currentUploadFile.fileName].push({
          uid: self.currentUploadFile.require.file.uid,
          fileType: e.data.response.data.fileType,
          name: e.data.response.data.name,
          fileName: e.data.response.data.name,
          url: e.data.response.data.url,
          path: e.data.response.data.url
        })
        self.$refs.formData.validateField(self.currentUploadFile.fileName)
      } else if (e.data.webInfo.requestId === self.addDriverFileRequestId) {
        if (e.data.response.success) {
          self.$message.success('上传驱动模板文件成功')
          self.$emit('submit')
          self.closeForm()
        } else {
          self.$message.error(e.data.response.message)
        }
      }
    },
    is(currentProjectData) {
      this.dialogVisible = true
      this.formData = {
        driverLibraryId: currentProjectData.driverLibraryId,
        relationTypeId: '',
        driverFiles: []
      }
      this.$nextTick(() => {
        this.$refs.formData.clearValidate()
      })
    },
    handleExceed(files) {
      this.$refs.driverFiles.clearFiles()
      this.handleUploadFiles({ file: files[0] }, 'driverFiles')
    },
    // 上传前校验
    handleCheck(params) {
      var suffix = params.file.name.substring(params.file.name.lastIndexOf('.')) // .txt
      const isLimit = params.file.size / 1024 / 1024 < 20
      if (this.uploadFileType) {
        if ([this.uploadFileType].includes(suffix)) {
          if (!isLimit) {
            this.$message.error('上传文件大小不能超过 20MB!')
            return false
          } else {
            return true
          }
        } else {
          this.$message.error('上传文件不符合上传格式!')
          return false
        }
      } else {
        if (!isLimit) {
          this.$message.error('上传文件大小不能超过 20MB!')
          return false
        } else {
          return true
        }
      }
    },
    // 图片上传
    handleUploadFiles(require, fileName) {
      let fileDom = this.$refs[fileName].uploadFiles
      let uploadFilesLast = fileDom.length - 1
      let check = this.handleCheck(require)
      if (!check) {
        fileDom.splice(uploadFilesLast, 1)
        return
      }
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.currentUploadFile = { require, fileName }
        let self = this
        this.uploadFileRequestId = generateUUID()
        let reader = new FileReader() // new一个FileReader实例
        reader.readAsDataURL(require.file)
        reader.onload = function () {
          //   读取文件获得的对象
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/files/upload',
            RequestMethod: 'POST',
            Headers: {
              // contentType: 'multipart/form-data',
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: {
              fileName: require.file.name,
              fileContent: reader.result.split(',')[1]
            },
            WebInfo: {
              requestId: self.uploadFileRequestId
            }
          }
          postMessage(message)
        }
      } else {
        let formData = new FormData()
        formData.append('file', require.file)
        uploadFile(formData)
          .then((res) => {
            this.formData[fileName].push({
              uid: require.file.uid,
              fileType: res.data.fileType,
              name: res.data.name,
              fileName: res.data.name,
              url: res.data.url,
              path: res.data.url
            })
            this.$refs.formData.validateField(fileName)
          })
          .catch(() => {
            fileDom.splice(uploadFilesLast, 1)
            this.$message.error('上传失败')
          })
      }
    },
    handleRemove(fileName) {
      this.formData[fileName] = []
    },
    handleClose() {
      this.$refs.driverFiles?.clearFiles()
    },
    closeForm() {
      this.dialogVisible = false
      this.$emit('closeForm')
    },
    submitForm() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          if (defaultSettings.isWPF || defaultSettings.isCEF) {
            this.addDriverFileRequestId = generateUUID()
            let message = {
              RequestUrl: process.env.VUE_APP_URL + '/driverLibrary/addDriverFile',
              RequestMethod: 'POST',
              Headers: {
                contentType: 'application/json'
              },
              QueryParameter: {},
              RequestBody: this.formData,
              WebInfo: {
                requestId: this.addDriverFileRequestId
              }
            }
            postMessage(message)
          } else {
            addDriverFile(this.formData).then((res) => {
              if (res.success) {
                this.$message.success('上传驱动模板文件成功')
                this.$emit('submit')
                this.closeForm()
              } else {
                this.$message.error(res.message)
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.driverPrgramForm {
  /deep/label {
    font-weight: 500;
  }
}
</style>
